package gallery

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"io"
	"net"
	"os"
)
import pb "ReferenceMonitor/sdk/rpc/pb_gen"

func StartGalleryService(addr string, path string) {
	lis, err := net.Listen("tcp", addr)
	if err != nil {
		fmt.Println("Start Gallery Service Failed: ", err)
		return
	}
	grpcServer := grpc.NewServer()
	pb.RegisterGalleryServer(grpcServer, NewServerRpc(path))
	grpcServer.Serve(lis)
}

type ServerRPC struct {
	pb.UnimplementedGalleryServer
	filePath string
}

func NewServerRpc(dir string) *ServerRPC {
	return &ServerRPC{
		filePath: dir,
	}
}

func (s *ServerRPC) Version(ctx context.Context, in *pb.String) (*pb.String, error) {
	return &pb.String{
		Content: Version,
	}, nil
}

func (s *ServerRPC) GetPictureList(ctx context.Context, picReq *pb.PictureRequest) (*pb.PictureList, error) {
	files := getPictureList(s.filePath)
	var pic []*pb.Picture
	for _, fi := range files {
		pic = append(pic, &pb.Picture{
			Name: fi,
			//Thumbnail: fi,
		})
	}
	req := &pb.PictureList{
		Pictures: pic,
		Status:   1,
	}
	return req, nil
}

func (s *ServerRPC) Download(picReq *pb.PictureRequest, stream pb.Gallery_DownloadServer) error {
	//fi := picReq.Path
	fmt.Println("Try to Download File: ", picReq.Gallery, picReq.Path)
	file, err := os.OpenFile(picReq.Path, os.O_RDWR, 0755)

	if err != nil {
		fmt.Println("Failed to open file: ", picReq.Path, err)
		return err
	}
	buf := make([]byte, 1024)
	for {
		n, err := file.Read(buf)
		if err != nil {
			if err == io.EOF {
				err = nil
				break
			}
		}
		err = stream.Send(&pb.Chunk{
			Content: buf[0:n],
		})
		if err != nil {
			fmt.Println("Failed to send file: ", err)
			return err
		}
	}
	//status, err := stream.Send
	return nil
}
